package com.asen.commons.core.jdbc.builder.mysql.filter;

import com.asen.commons.core.jdbc.param.SqlColumn;
import com.asen.commons.core.jdbc.param.SqlContextManager;
import com.asen.commons.core.meta.dao.FilterItem;
import com.asen.commons.core.meta.enums.FilterSymbolEnum;

/**
 * Like过滤解析器
 *
 * @author Gary
 * @version 1.0
 * @date 2021-08-22
 */
public class DefaultFilterParser implements FilterParser {

    @Override
    public CharSequence parse(SqlContextManager contextManager, FilterItem filterItem) {
        SqlColumn sqlColumn = contextManager.getSqlColumn(filterItem.getFieldName());
        if (sqlColumn == null) {
            return "";
        }

        FilterSymbolEnum filterSymbol = filterItem.getSymbol();
        StringBuilder sql = new StringBuilder();
        if (FilterSymbolEnum.EQUAL_IGNORE_CASE == filterSymbol) {
            sql.append("upper(").append(sqlColumn.getFullColumn()).append(")");
        } else {
            sql.append(sqlColumn.getFullColumn());
        }
        sql.append(filterSymbol.getDesc());

        Object value = filterItem.getValue();
        if (value != null) {
            if (FilterSymbolEnum.EQUAL_IGNORE_CASE == filterSymbol) {
                sql.append("upper(?)");
            } else {
                sql.append("?");
            }
            contextManager.setParam(sqlColumn.getJavaType(), value);
        } else {
            sql.append("null");
        }

        return sql;
    }

}
